<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">新闻详情</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" />
    </view>

    <!-- 新闻内容 -->
    <scroll-view
      class="content-scroll"
      scroll-y
      v-else-if="newsDetail"
      enhanced
      :show-scrollbar="false"
      :enable-back-to-top="true"
      :bounces="true"
      :fast-deceleration="false"
    >
      <view class="news-detail">
        <!-- 新闻头部 -->
        <view class="news-header">
          <text class="news-title">{{ newsDetail.title }}</text>
          <view class="news-meta">
            <text class="news-author">{{ newsDetail.author }}</text>
            <text class="news-time">{{ formatDateTime(newsDetail.publishTime) }}</text>
            <view class="news-stats">
              <view class="stat-item">
                <uni-icons type="eye" size="12" color="#999"></uni-icons>
                <text class="stat-text">{{ formatNumber(newsDetail.viewCount) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 新闻封面 -->
        <view class="news-cover" v-if="newsDetail.coverImage">
          <image
            :src="newsDetail.coverImage"
            mode="widthFix"
            class="cover-image"
          />
        </view>

        <!-- 新闻正文 -->
        <view class="news-content">
          <rich-text :nodes="formatContent(newsDetail.content)"></rich-text>
        </view>

        <!-- 点赞 -->
        <view class="news-actions">
          <view
            class="action-btn"
            :class="{ active: newsDetail.isLiked }"
            @click="toggleLike"
          >
            <uni-icons
              :type="newsDetail.isLiked ? 'heart-filled' : 'heart'"
              size="20"
              :color="newsDetail.isLiked ? '#ff4757' : '#666'"
            />
            <text class="action-text">{{ formatNumber(newsDetail.likeCount) }}</text>
          </view>
        </view>
      </view>

      <!-- 评论区 -->
      <CommentSection :newsId="newsId" />
    </scroll-view>

    <!-- 错误状态 -->
    <view class="error-container" v-else>
      <uni-icons type="info" size="48" color="#ddd"></uni-icons>
      <text class="error-text">加载失败，请重试</text>
      <button class="retry-btn" @click="loadNewsDetail">重试</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { newsApi } from '@/api/index.js'
import { formatDateTime, formatNumber } from '@/utils/format.js'
import CommentSection from './components/CommentSection.vue'

// 响应式数据
const statusBarHeight = ref(0)
const newsId = ref(null)
const newsDetail = ref(null)
const isLoading = ref(true)

// 使用 scroll-view 内置功能，无需额外处理

// 页面加载
onLoad((options) => {
  newsId.value = parseInt(options.id)
  if (newsId.value) {
    loadNewsDetail()
  }
})

// 页面初始化
onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
})

// 加载新闻详情
const loadNewsDetail = async () => {
  if (!newsId.value) return

  try {
    isLoading.value = true
    const response = await newsApi.getNewsDetail(newsId.value)

    if (response.code === 200) {
      newsDetail.value = response.data
    } else {
      throw new Error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载新闻详情失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 切换点赞状态
const toggleLike = async () => {
  if (!newsDetail.value) return

  try {
    const response = await newsApi.likeNews(newsId.value)

    if (response.code === 200) {
      newsDetail.value.isLiked = !newsDetail.value.isLiked
      newsDetail.value.likeCount += newsDetail.value.isLiked ? 1 : -1
    }
  } catch (error) {
    console.error('点赞失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 格式化内容
const formatContent = (content) => {
  if (!content) return ''

  // 简单的 HTML 格式化，将换行符转换为 <br> 标签
  return content.replace(/\n/g, '<br/>')
}

// scroll-view 内置滚动处理，无需额外代码
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%);
  display: flex;
  flex-direction: column;
}

.status-bar {
  background: #ffffff;
}

.nav-bar {
  display: flex;
  align-items: center;
  position: relative;
  padding: 20rpx 30rpx;
  background: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.nav-left {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  left: 30rpx;
  z-index: 1;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  flex: 1;
  text-align: center;
}

.content-scroll {
  flex: 1;
  height: 0;
  /* 使用 scroll-view 时不设置 overflow */
  /* 确保滚动容器能正确处理触摸事件 */
  -webkit-overflow-scrolling: touch;
  /* 确保触摸事件正常工作 */
  touch-action: manipulation;
  /* 优化渲染性能 */
  transform: translateZ(0);
  will-change: scroll-position;
}

.loading-container, .error-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 30rpx;
}

.error-text {
  font-size: 28rpx;
  color: #999999;
}

.retry-btn {
  background: #4CAF50;
  color: #ffffff;
  border: none;
  border-radius: 20rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.news-detail {
  background: #ffffff;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.news-header {
  padding: 40rpx 30rpx 30rpx;
}

.news-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  margin-bottom: 30rpx;
}

.news-meta {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex-wrap: wrap;
}

.news-author {
  font-size: 26rpx;
  color: #4CAF50;
  font-weight: 500;
}

.news-time {
  font-size: 24rpx;
  color: #999999;
}

.news-stats {
  display: flex;
  gap: 20rpx;
  margin-left: auto;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.stat-text {
  font-size: 22rpx;
  color: #999999;
}

.news-cover {
  width: 100%;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  display: block;
}

.news-content {
  padding: 30rpx;
  font-size: 30rpx;
  line-height: 1.8;
  color: #333333;
}

.news-actions {
  display: flex;
  align-items: center;
  gap: 40rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx 24rpx;
  border-radius: 24rpx;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.action-btn.active {
  background: rgba(255, 71, 87, 0.1);
}

.action-text {
  font-size: 26rpx;
  color: #666666;
}

.action-btn.active .action-text {
  color: #ff4757;
}
</style>
